import React, { useState } from "react";
import * as commonUtil from "../../../utils/commonUtil";
import * as documentService from "../services/documentService";
import * as advanceService from "../services/advanceService";

export default function useAdvanceState() {

    const [loading, setLoading] = useState(false);
    const [textChatMessages, setTextChatMessages] = useState([
      { id: commonUtil.generateUUID(), type: "ai", think: "", content: "你好！我是TaiXu智能，欢迎使用智能检索RAG！" },
    ]);
    const [documentTotal, setDocumentTotal] = useState(0);
    const [documentList, setDocumentList] = useState([]);
    const [selectedDocument, setSelectedDocument] = useState([]);
    const [selectedPattern, setSelectedPattern] = useState(null);
    const [focusBlurFlag, setFocusBlurFlag] = useState(false);
    const [completeStatus, setCompleteStatus] = useState("running");    // running：等待输入或运行中；finish：完成
    const [workflowGraph, setWorkflowGraph] = useState(false);

    const onSendChat = (values, query) => {
        setLoading(true);
        textChatMessages.push({ id: commonUtil.generateUUID(), type: "user", think: "", content: query });
        const msgId = commonUtil.generateUUID();
        textChatMessages.push({ id: msgId, type: "ai", think: "", content: "正在思考中。。。。。。" });
        setTextChatMessages(textChatMessages);

        let params = { msgId, query: query, ...values };
        advanceService.retrievalAdvance(params).then(res => {
            if (res.code == 200) {
                const data = res.data?.chain_result;
                let newTextObj = textChatMessages.find(item => msgId == item.id);
                if (data.indexOf("<think>") > -1) {
                    newTextObj.think = newTextObj.think + res;
                }
                newTextObj.content = data;
                setTextChatMessages(textChatMessages);
                setLoading(false);
            }
        });
    }

    const loadDocumentList = ({ current_page, page_size }) => {
        documentService.getDocumentList({ current_page, page_size }).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setDocumentTotal(data.total);
                setDocumentList(data.records);
            }
        });
    }

    return {
        loading, setLoading,
        textChatMessages, setTextChatMessages,
        documentTotal, setDocumentTotal,
        documentList, setDocumentList,
        selectedDocument, setSelectedDocument,
        selectedPattern, setSelectedPattern,
        focusBlurFlag, setFocusBlurFlag,
        completeStatus, setCompleteStatus,
        workflowGraph, setWorkflowGraph,
        onSendChat, loadDocumentList
    };
}
